package com.yenlien.traceyun.usercenter.controller;

import com.yenlien.traceyun.common.utils.FileUtil;
import com.yenlien.traceyun.usercenter.service.FileService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.exception.BusinessException;
import com.yenlien.traceyun.webase.exception.ErrorPageException;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-07-21
 * @description:
 **/
@RestController
@RequestMapping(value = "/file")
public class FileController extends BaseController {
    public static final String ROOT = "upload";
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private FileService fileService;

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Object upload(HttpServletRequest request) throws IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        StringBuilder address = new StringBuilder();
        if (files != null && files.size() > 0) {
            for (MultipartFile file : files) {
                address.append(fileService.upload(file)).append(";");
            }
        }
        if (address.length() > 0) {
            return address.substring(0, address.length() - 1);
        }
        throw new BusinessException("5000", "路径和文件名错误");
    }

    @RequestMapping(value = "/delete/{filename}", method = RequestMethod.GET)
    public Object delete(@PathVariable("filename") String filename) throws IOException {
        fileService.deleteFile(filename);
        return success("success");
    }

    @ResponseBody
    @RequestMapping(value = "/show/{filename:.+}")
    public void loadFile(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException, ErrorPageException {
        BufferedInputStream in = null;
        ByteArrayOutputStream bos = null;
        String ys = request.getParameter("ys");
        try {
            File file = resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()).getFile();
            bos = new ByteArrayOutputStream();
            String suf = FileUtil.getSuffix(filename).toLowerCase();
            //开启图片压缩
            if (ys != null && ys.equals("1")) {
                Thumbnails.of(file).forceSize(160, 160).outputQuality(0.1f).toOutputStream(response.getOutputStream());
                return;
            }
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            if (suf.contains("png") || suf.contains("jpg") || suf.contains("gif") || suf.contains("JPEG")) {
                response.setContentType("image/png");
            } else {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            }
            response.getOutputStream().write(bos.toByteArray());
        } catch (IOException e) {
            throw new ErrorPageException("文件【" + filename + "】不存在");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
